/*
 * Copyright (c) 2020-2021, Bluetrum Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021/10/21     AlgoIdeas    The first version
 */

#include <rtthread.h>
#include <board.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <dfs_posix.h>

#include "track.h"
#include "gpx.h"

static int fd = 0;
static rt_uint8_t trackActive = 0;


static int track_write(const char* str)
{
    int res = write(fd, str, strlen(str));

    return res;
}


void track_start()
{
    if (trackActive) {
        rt_kprintf("Track started!\n");
        return ;
    }

    rt_kprintf("Track start");

    char filepath[128] = {0};
    time_t now = time(NULL);
    struct tm* timeInfo;
    timeInfo = localtime(&now);

    sprintf(filepath, "TRACK_%d%02d%02d_%02d%02d%02d.gpx", timeInfo->tm_year + 1900, timeInfo->tm_mon + 1,
            timeInfo->tm_mday, timeInfo->tm_hour, timeInfo->tm_min, timeInfo->tm_sec);

    rt_kprintf("Track file %s\n", filepath);

    fd = open(filepath, O_CREAT | O_RDWR | O_APPEND);
    if (-1 != fd)
    {
        rt_kprintf("file %s open success\n", filepath);

        gpx_setMetaName("Ver 1.0.0");
        gpx_setMetaDesc("GPS Track By AlgoIdeas");
        gpx_setName(filepath);
        gpx_setDesc("GPS Track based on AB32VG1");

        track_write(gpx_getOpen());

        char data[256] = {0};
        gpx_getMetaData(data);
        track_write(data);

        track_write(gpx_getTrakOpen());

        char info[256] = {0};
        gpx_getInfo(info);
        track_write(info);

        track_write(gpx_getTrakSegOpen());

        trackActive = true;
    }
    else
    {
        trackActive = false;
        rt_kprintf("Track file open error!\n");
    }
}

void track_point(GPS_Info_t gpsInfo)
{
    if (!trackActive) {
        return ;
    }

    rt_kprintf("Recording...\n");

    char timeBuf[64] = {0};
    char strBuf[8] = {0};
    char pointBuf[256] = {0};
    char longitudeBuf[16] = {0};
    char latitudeBuf[16] = {0};

    snprintf(timeBuf, sizeof(timeBuf),  "%d-%02d-%02dT%02d:%02d:%02dZ",
            gpsInfo.clock.year, gpsInfo.clock.month, gpsInfo.clock.day,
            gpsInfo.clock.hour, gpsInfo.clock.minute, gpsInfo.clock.second);

    sprintf(strBuf, "%.2f", gpsInfo.altitude);
    gpx_setEle(strBuf);
    gpx_setTime(timeBuf);

    sprintf(longitudeBuf, "%.6f", gpsInfo.longitude);
    sprintf(latitudeBuf, "%.6f", gpsInfo.latitude);
    gpx_getPt(GPX_TRKPT, longitudeBuf, latitudeBuf, pointBuf);
    rt_kprintf("%s\n", pointBuf);

    track_write(pointBuf);
}

void track_stop()
{
    if (!trackActive) {
        rt_kprintf("Track stoped!\n");
        return ;
    }

    rt_kprintf("Track stop");

    trackActive = false;

    track_write(gpx_getTrakSegClose());;
    track_write(gpx_getTrakClose());
    track_write(gpx_getClose());

    close(fd);

    rt_kprintf("Track record end");
}

